package com.rickpan.controller;

import com.rickpan.dto.common.ApiResponse;
import com.rickpan.dto.request.CreateWorkRecordRequest;
import com.rickpan.dto.request.UpdateWorkRecordRequest;
import com.rickpan.dto.response.WorkRecordResponse;
import com.rickpan.service.WorkRecordService;
import com.rickpan.utils.SecurityUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.List;

/**
 * 工作记录控制器
 */
@RestController
@RequestMapping("/api/work-reports/records")
@Tag(name = "工作记录管理", description = "工作记录相关接口")
public class WorkRecordController {

    private static final Logger logger = LoggerFactory.getLogger(WorkRecordController.class);

    @Autowired
    private WorkRecordService workRecordService;



    /**
     * 创建工作记录
     */
    @PostMapping
    @Operation(summary = "创建工作记录", description = "创建新的工作记录")
    public ApiResponse<WorkRecordResponse> createWorkRecord(
            HttpServletRequest request,
            @Valid @RequestBody CreateWorkRecordRequest createRequest) {
        
        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("创建工作记录，用户ID: {}, 标题: {}", userId, createRequest.getTitle());

        WorkRecordResponse workRecord = workRecordService.createWorkRecord(userId, createRequest);
        return ApiResponse.success(workRecord, "工作记录创建成功");
    }

    /**
     * 更新工作记录
     */
    @PutMapping("/{recordId}")
    @Operation(summary = "更新工作记录", description = "更新指定的工作记录")
    public ApiResponse<WorkRecordResponse> updateWorkRecord(
            HttpServletRequest request,
            @Parameter(description = "记录ID", required = true) @PathVariable Long recordId,
            @Valid @RequestBody UpdateWorkRecordRequest updateRequest) {

        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("更新工作记录，用户ID: {}, 记录ID: {}", userId, recordId);

        WorkRecordResponse workRecord = workRecordService.updateWorkRecord(userId, recordId, updateRequest);
        return ApiResponse.success(workRecord, "工作记录更新成功");
    }

    /**
     * 删除工作记录
     */
    @DeleteMapping("/{recordId}")
    @Operation(summary = "删除工作记录", description = "删除指定的工作记录")
    public ApiResponse<Void> deleteWorkRecord(
            HttpServletRequest request,
            @Parameter(description = "记录ID", required = true) @PathVariable Long recordId) {
        
        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("删除工作记录，用户ID: {}, 记录ID: {}", userId, recordId);

        workRecordService.deleteWorkRecord(userId, recordId);
        return ApiResponse.<Void>success("工作记录删除成功");
    }

    /**
     * 获取工作记录详情
     */
    @GetMapping("/{recordId}")
    @Operation(summary = "获取工作记录详情", description = "根据ID获取工作记录详情")
    public ApiResponse<WorkRecordResponse> getWorkRecord(
            HttpServletRequest request,
            @Parameter(description = "记录ID", required = true) @PathVariable Long recordId) {
        
        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("获取工作记录详情，用户ID: {}, 记录ID: {}", userId, recordId);

        WorkRecordResponse workRecord = workRecordService.getWorkRecord(userId, recordId);
        return ApiResponse.success(workRecord, "获取工作记录成功");
    }

    /**
     * 分页查询用户的工作记录
     */
    @GetMapping
    @Operation(summary = "分页查询工作记录", description = "分页查询用户的工作记录")
    public ApiResponse<Page<WorkRecordResponse>> getUserWorkRecords(
            HttpServletRequest request,
            @Parameter(description = "页码，从0开始") @RequestParam(defaultValue = "0") int page,
            @Parameter(description = "页大小") @RequestParam(defaultValue = "20") int size,
            @Parameter(description = "搜索关键词") @RequestParam(required = false) String keyword,
            @Parameter(description = "分类ID") @RequestParam(required = false) Long categoryId,
            @Parameter(description = "状态") @RequestParam(required = false) String status,
            @Parameter(description = "优先级") @RequestParam(required = false) String priority,
            @Parameter(description = "开始日期") @RequestParam(required = false) String startDate,
            @Parameter(description = "结束日期") @RequestParam(required = false) String endDate) {

        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("分页查询工作记录，用户ID: {}, 页码: {}, 页大小: {}, 关键词: {}, 分类: {}, 状态: {}, 优先级: {}",
                   userId, page, size, keyword, categoryId, status, priority);

        Page<WorkRecordResponse> workRecords = workRecordService.getUserWorkRecords(
            userId, page, size, keyword, categoryId, status, priority, startDate, endDate);
        return ApiResponse.success(workRecords, "获取工作记录列表成功");
    }

    /**
     * 根据日期查询工作记录
     */
    @GetMapping("/by-date")
    @Operation(summary = "按日期查询工作记录", description = "根据指定日期查询工作记录")
    public ApiResponse<List<WorkRecordResponse>> getWorkRecordsByDate(
            HttpServletRequest request,
            @Parameter(description = "查询日期", required = true) 
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate date) {
        
        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("按日期查询工作记录，用户ID: {}, 日期: {}", userId, date);

        List<WorkRecordResponse> workRecords = workRecordService.getWorkRecordsByDate(userId, date);
        return ApiResponse.success(workRecords, "获取工作记录成功");
    }

    /**
     * 根据日期范围查询工作记录
     */
    @GetMapping("/by-date-range")
    @Operation(summary = "按日期范围查询工作记录", description = "根据日期范围查询工作记录")
    public ApiResponse<List<WorkRecordResponse>> getWorkRecordsByDateRange(
            HttpServletRequest request,
            @Parameter(description = "开始日期", required = true) 
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
            @Parameter(description = "结束日期", required = true) 
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
        
        Long userId = SecurityUtils.getCurrentUserId();
        logger.info("按日期范围查询工作记录，用户ID: {}, 开始日期: {}, 结束日期: {}", userId, startDate, endDate);

        List<WorkRecordResponse> workRecords = workRecordService.getWorkRecordsByDateRange(userId, startDate, endDate);
        return ApiResponse.success(workRecords, "获取工作记录成功");
    }
}
